package com.qingcloud.adminbackend.command;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RuntimeUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * mavena相关工具
 */
@Slf4j
public class MavenTools {

    /**
     * 组件根目录
     */
    public volatile static String WORK_ROOT = "/app/service/command";

    //maven命令行路径
    public volatile static String MVN_PATH = "/opt/apache-maven-3.8.6/bin/mvn";

    //下载依赖参数
    private static final String DOWNLOAD_PARAM = " dependency:copy-dependencies -DoutputDirectory=libs -DincludeScope=runtime";

    private MavenTools() {
    }

    /**
     * 根据pom文件内容，下载所有依赖
     *
     * @param pom     pom文件内容
     * @param workDir 工作目录
     * @return 所有依赖jar文件完整路径
     */
    public static List<String> downloadDependencies(String pom, String workDir) {
        if (StrUtil.isBlank(pom)) {
            return Collections.emptyList();
        }
        //在工作目录创建pom.xml文件
        List<String> dependencies = new ArrayList<>();
        try {
            //依赖包目录
            String libParent = workDir + "/libs";
            FileUtil.del(libParent);
            FileUtil.mkdir(libParent);
            //生成pom文件
            String pomFile = workDir + "/pom.xml";
            FileUtil.writeUtf8String(pom, pomFile);
            //执行mvc命令下载依赖
            Process process = RuntimeUtil.exec(null, new File(workDir), MVN_PATH + DOWNLOAD_PARAM);
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    log.info(line);
                }
            }
            process.waitFor();
            dependencies = FileUtil.listFileNames(libParent).stream().map(it -> libParent + "/" + it).collect(Collectors.toList());
        } catch (Exception e) {
            log.info(e.getMessage(), e);
        }
        return dependencies;
    }

    /**
     * 获取组件工作根目录
     *
     * @param id          组件ID
     * @param projectName 项目英文名
     * @return 组件名称
     */
    public static String getComponentWorkDir(Integer id, String projectName) {
        String dir = StrUtil.format("{}/{}-{}", WORK_ROOT, projectName, id);
        if (!FileUtil.exist(dir)) {
            FileUtil.mkParentDirs(dir);
        }
        return dir;
    }

}
